local skynet = require "skynet"
local mysql = require "mysql"
local snax = require "snax"
local cluster = require "cluster"
local CMD = require "center_proto"
local httpc = require "http.httpc"
local db = require "dblib"

local REGPHONESER = {}

local SMSConfig = {
    appid = '16104',
    signature = '84cce091bd93681b033339f730b6a12d',
    content = '【麟云科技有限公司】您的验证码是：%s(5分钟内有效)',
    host = 'api.mysubmail.com',
    url = '/message/send'
}

local VerifyCode = {
}


--************************手机号码注册服务*************************************

function GenerateVerifyCode()
    return ''..math.random(100000, 999999)
end


function REGPHONESER.HadRegistered(playId)     --查询是否注册过
    playId = playId
    local bReg = false
    local temp = {[true] = 1, [false] = 2}
    
    local res1,res2 = db.call("call pr_GetUserPhone("..tonumber(playId)..",@a,@b);", "select @a,@b;")
    local phoneHadReg
    if res2 and res2[1] and res2[1]['@b'] == 1 then 
        bReg = true 
        phoneHadReg = res2[1]['@a']    --有绑定手机
        skynet.error('This user Had Reg a phone', phoneHadReg)
    end
    
    local msgRet
    if bReg then msgRet = string.pack('bc11', temp[bReg], phoneHadReg) 
    else msgRet = string.pack('b', temp[bReg]) end
    local re = {mcmd = CMD.Main_RegPhoneSer_module,scmd = CMD.Sub_RequryHadRegisterdResp, msg = msgRet} 
    return re
end

function REGPHONESER.SendVerificationCode(playId, phoneNum)   --请求短信并发送验证码
    local bSuc = true
    local temp = {[true] = 1, [false] = 2}
    local re = {mcmd = CMD.Main_RegPhoneSer_module,scmd = CMD.Sub_SendVerificationCodeResp, msg = string.pack('b', temp[bSuc])} 
    local res1,res2 = db.call("call pr_checkPhone("..phoneNum..",@a);", "select @a;")
    local phoneHasBind
    if res2 and res2[1] and res2[1]['@a'] == 1 then --绑定了
        phoneHasBind = true
        skynet.error('This phoneNum Had Reg', phoneNum)
    end
    if not phoneHasBind then 
        local recvheader = {}
        local form = {}
        form.appid = SMSConfig.appid
        form.signature = SMSConfig.signature
        form.host = SMSConfig.host
        form.url = SMSConfig.url
        form.to = ''..phoneNum
        local verifyCode = GenerateVerifyCode()
        skynet.error('GenerateVerifyCode is ', verifyCode)
        form.content = string.format(SMSConfig.content, verifyCode)
        local status, body =  httpc.post(SMSConfig.host, SMSConfig.url, form, recvheader)
        local postRet = string.find(body, "\"status\":\"success\"")
        if not postRet then bSuc = false 
        else 
            VerifyCode[verifyCode] = {t = os.time(), code = verifyCode}
        end
        skynet.error('RegPhone http request ', 'ret is', bSuc, 'phone is ', phoneNum, ' content is ', form.content, ' status is', status, ' body is ', body)
        re.msg = string.pack('b', temp[bSuc])
    else
        re.msg = string.pack('b', 3)
    end
    return re
end

function REGPHONESER.RegisterPhone(playId, msg)    --插入数据库
    local phoneNum = string.sub(msg, 1, 11)
    local verifyCode = string.sub(msg, 12)                           --12位起是verifyCode
    local ret = 4                                                    --1成功,2验证码失效,3验证码错误,4其他错误
    if VerifyCode[verifyCode] then 
        if VerifyCode[verifyCode].code ~= verifyCode then ret = 3    --验证码不匹配
        else
            if (VerifyCode[verifyCode].t - os.time() < 60 * 5) then ret = 1
            else ret = 2 end
        end
    end
    skynet.error('VerifyCode Ret is [1 indicate suc]', ret)
    local jia = 0
    if ret == 1 then    --验证成功了就插入
        local str = "call pr_PutUserPhone("..tonumber(playId)..",\""..phoneNum.."\",@a);".."select @a"
        skynet.error('regphone proc '..str)

        local res1,res2 = db.call("call pr_PutUserPhone("..tonumber(playId)..",\""..phoneNum.."\",@a);", "select @a")
        
        if res2 and res2[1] and res2[1]['@a'] == 1 then jia = 1 end  --第一次绑定
        skynet.error('regphone pr_PutUserPhone ret, jia == ', jia)
        VerifyCode[verifyCode] = nil
    end
    
    local re = {mcmd = CMD.Main_RegPhoneSer_module,scmd = CMD.Sub_RequstBindPhoneResp, msg = string.pack('bbc11', ret, jia, phoneNum)}
    return re
end

function response.request_regPhone(conf)   --{cmd,playid,msg}
    
    skynet.error("[register_phone_ser] request_msg ",conf.playid,conf.cmd,conf.msg)

    if conf.cmd == CMD.Sub_RequryHadRegisterdReq then               --查询是否注册过
        return REGPHONESER.HadRegistered(conf.playid)
        
    elseif conf.cmd == CMD.Sub_SendVerificationCodeReq then         --获取验证码请求
        return REGPHONESER.SendVerificationCode(conf.playid, conf.msg)
            
    elseif conf.cmd == CMD.Sub_RequstBindPhoneReq then              --绑定手机请求
        return REGPHONESER.RegisterPhone(conf.playid, conf.msg)
    end 
    
end



function REGPHONESER.start(...)

    --centerserver = cluster.snax("center", "centerser")
end


function init( ... )
	skynet.error("register_phone_ser server start:")
	snax.enablecluster()
    REGPHONESER.start(...)
end

function exit(...)
	skynet.error ("register_phone_ser server exit:", ...)
end